package com.lottery.game.interceptor;

import com.lottery.game.annotation.Current;
import com.lottery.game.common.utils.MapUtils;
import com.lottery.game.core.model.dto.UserToken;
import com.lottery.game.core.modules.service.app.v2.PassportService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

import static com.lottery.game.common.constants.GameConstants.TICKET_KEY;

public class CurrentMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private PassportService passportService;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Current.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        return MapUtils.mapToObject(passportService.checkToken(request.getHeader(TICKET_KEY)), UserToken.class);
    }
}
